package com.lin.csdn.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

public class PoolConnection implements InvocationHandler {
    private final static String CLOSE = "close";
    private static final Class<?>[] IFACES = new Class<?>[] { Connection.class };

    private final PoolDataSource dataSource;
    private final Connection realConnection;
    private final Connection proxyConnection;
    private long keepAliveTime;

    public PoolConnection(Connection conn, PoolDataSource dataSource) {
        this.dataSource = dataSource;
        this.realConnection = conn;
        this.proxyConnection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), IFACES, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        if (CLOSE.equals(methodName)) {  // 对close方法进行拦截
            dataSource.pushConnection(this); // 放回数据库连接池中
            return null;
        }
        return method.invoke(realConnection, args);
    }

    public Connection getRealConnection() {
        return realConnection;
    }

    public Connection getProxyConnection() {
        return proxyConnection;
    }

    public long getKeepAliveTime() {
        return System.currentTimeMillis() - keepAliveTime;
    }

    public void setKeepAliveTime(long keepAliveTime) {
        this.keepAliveTime = keepAliveTime;
    }
}
